<?php

namespace app\admin\controller;

use think\facade\Db;
use app\common\model\admin\AuthRule as AuthRuleModel;

class AuthRule extends Base
{

    protected $tb = "auth_rule";

    /**
     * 查看
     */
    public function index()
    {
        
        $where = [];
        $searchKey = input('searchkey')?input('searchkey'):'';
        if ($searchKey){
            $where[] = [
                'title','like','%'.$searchKey.'%'
            ];
        }
        $authroleData = Db::name($this->tb)->where(['status' => 1])->where($where)->order('id desc')->select()->toArray();
        $AuthRuleModel = new AuthRuleModel();
        $ruleDataTree = $AuthRuleModel->sort($authroleData);
    
        return view('admin/authrule', [
            'tb' => $this->tb,
            'authroleData' => $authroleData,
            'ruleDataTree' => $ruleDataTree,
            'searchkey' => $searchKey
        ]);
    }

    /**
     * 新增
     */
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $res = Db::name($this->tb)->insert($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        $authroleData = Db::name($this->tb)->where(['status' => 1])->order('id desc')->select()->toArray();
        $AuthRuleModel = new AuthRuleModel();
        $ruleDataTree = $AuthRuleModel->sort($authroleData);
        return view('admin/authrule_add',[
            'ruleDataTree' => $ruleDataTree,
            'authroleData' => $authroleData,
        ]);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        if (request()->isPost()) {
            $data = input('post.');
            $res = Db::name($this->tb)->update($data);
            if ($res) {
                return alert('操作成功', 'index', 6);
            } else {
                return alert('操作失败', 'index', 5);
            }
        }
        $id = input('id');
        $ruleData = Db::name($this->tb)->where(['id'=>$id])->find();
        $authroleData = Db::name($this->tb)->where(['status' => 1])->order('id desc')->select()->toArray();
        $AuthRuleModel = new AuthRuleModel();
        $ruleDataTree = $AuthRuleModel->sort($authroleData);
        return view('admin/authrule_edit',[
            'ruleDataTree' => $ruleDataTree,
            'authroleData' => $authroleData,
            'ruleData'  => $ruleData,
        ]);
    }

}
